<?php

namespace app\admin\model;

use think\Model;
use think\Exception;
use think\Validate;
use app\common\library\Auth;

class UserIdCard extends Model
{

    

    

    // 表名
    protected $name = 'user_id_card';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function getCreateDateAttr($value, $data)
    {
        return human_date($data['createtime']);
    }

    public function getCreatetimeAttr($value, $data)
    {
        return datetime($data['createtime']);
    }

    public function getUpdatetimeAttr($value, $data)
    {
        return datetime($data['updatetime']);
    }

    // public function getIdCardAttr($value, $data)
    // {
    //     return explode(',', $data['id_card']);
    // }

    /**
     * 查看审核
     */
    public function index($user_id)
    {
        return $this->where('user_id',$user_id)->find();

    }
    

     /**
     * 添加审核
     * @param array $params
     * @return bool
     * @throws CommentException
     * @throws Exception
     */
    public static function postAdd($params = [])
    {
        
        $auth = $auth = Auth::instance();
        if($auth->is_sf){
            throw new Exception('已经认证通过，不需要在审核');
        }

        $rule = [
            'mobile|手机号'    => 'require|length:11',
            'name|姓名'       => 'require|length:2,10',
            'gender|性别'        => 'require|in:女,男',
            'occupation|职业' => 'require|length:2,20',
            'id_card|身份证'    => 'require',
            'addres|地址'    => 'require',
            'lng|经度'    => 'require',
            'lat|纬度'    => 'require',
        ];
        $message = [
            // 'content.length' => '评论最少输入3个字符'
        ];
        $validate = new Validate($rule);
        $result = $validate->check($params);
        if (!$result) {
            throw new Exception($validate->getError());
        }

        if(count(explode(",", $params['id_card'])) != 2){
            throw new Exception('身份证需要上传正反面2张');
        }

        
        $params['user_id'] = $auth->id;
        $model = new static();
        $id_card = $model->where(['user_id' => $auth->id])->find();
        if($id_card){
            if($id_card['status'] == 0 ){
                throw new Exception('还在审核中，请勿多次提交');
            }elseif($id_card['status'] == 1 ){
                throw new Exception('已经认证通过，不需要在审核提交');
            }
            $params['status'] = 0;
            $model->allowField(true)->save($params,['id'=>$id_card['id']]);
        }else{
            $model->allowField(true)->save($params);
        }

    }





    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
